package org.shuma.user.mng.Interceptor;

import com.google.gson.JsonObject;
import org.shuma.user.mng.utils.RedisUtil;
import org.shuma.user.utils.HttpCodeEnum;
import org.shuma.user.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * @author : liuming
 * @date : 2024/6/18 上午7:49
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorization = request.getHeader("Authorization");
        if (Objects.isNull(authorization) || Objects.isNull(redisUtil.getUserInfo(authorization))) {
            response.setContentType("application/json");
            Result<String> result = new Result<>();
            result.error(HttpCodeEnum.NEED_LOGIN, "");
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("code", HttpCodeEnum.NEED_LOGIN.getCode());
            jsonObject.addProperty("message", HttpCodeEnum.NEED_LOGIN.getMsg());
            jsonObject.addProperty("description", "");
            OutputStream ps = response.getOutputStream();
            //这句话的意思，使得放入流的数据是utf8格式
            ps.write(String.valueOf(jsonObject).getBytes(StandardCharsets.UTF_8));
//            response.getWriter().write();
            return false;
        }
        return true;
    }
}
